package com.kongwg.java;

/**
 *
 * 使用同步方法解决实现Runnable接口的线程安全问题
 * @author kongwg
 * @create 2020-12-05 15:02
 */
class Windows3 implements Runnable{
    private int ticket = 100;
    @Override
    public void run() {
        while (true){
            show();
            }
        }

    private synchronized void show() {
        if (ticket > 0){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "窗口卖出的票号为" + ticket);
            ticket--;
        }
    }
}




public class WindowsTest3 {
    public static void main(String[] args) {
        Windows1 w1 = new Windows1();

        Thread t1 = new Thread(w1);
        t1.setName("窗口1：");
        t1.start();
        Thread t2 = new Thread(w1);
        t2.setName("窗口2：");
        t2.start();
        Thread t3 = new Thread(w1);
        t3.setName("窗口3：");
        t3.start();
    }
}

